#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
using namespace std;
#include "common.h"

bool makefifo()
{
    // 1.创建命名管道文件
    int n = mkfifo(FIFENAME, 0666);
    if (n < 0)
    {
        cerr << "errno: " << errno << ". errstring" << strerror(errno) << endl;
        return false;
    }
    cout << "mkfifo success...." << endl;
    return true;
}

int main()
{
    // 打开文件，读取文件
Start:
    int rfd = open(FIFENAME, O_RDONLY);
    if (rfd < 0)
    {
        cerr << "errno: " << errno << ". errstring" << strerror(errno) << endl;
        if (makefifo())
            goto Start;
        else
            return 1;
    }
    cout << "open fifo success, read..." << endl;

    char buffer[1024];
    while (true)
    {
        ssize_t s = read(rfd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "client say: " << buffer << endl;
        }
        else if (s == 0)
        {
            cout << "client quit, server quit too!" << endl;
            break;
        }
    }

    close(rfd);
    cout << "close fifo success" << endl;
    return 0;
}